package com.zle.controller.login;
import java.util.Enumeration;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zle.common.cstn.GlobalConstants;
import com.zle.entity.User;
@Controller
public class LoginController extends LoginAbstractController{
	
	@RequestMapping("/login_show")
	public String loginShow(){
		return "/login/login";
	}
	@RequestMapping("/main_content")
	public String mainContentShow(){
		return "/main/mainContent";
	}
	@RequestMapping("/register")
	public String registerShow(){
		return "/login/register";
	}
	@RequestMapping("/login/login.action")
	public ModelAndView login(@RequestParam("username") String name , @RequestParam("password") String pwd,@RequestParam("captcha") String captcha,ModelAndView view){
		String k= (String)getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if(k.equals(captcha)){
			User user = getLoginService().checkUser(name, pwd);
			if(user == null){
				viewData.put("msg", "登录名或密码错误!");
				view.addAllObjects(viewData);
				//使用转发,不然页面EL表达式获取不到
				view.setViewName("forward:/login_show"); 
				return view;
			}else{
				user.setPwd(null);
				getSession().setAttribute(GlobalConstants.USER_SESSION, user); 
				getSession().setAttribute("uname", name);
				view.setViewName("forward:/main.action"); 
				return view;
			}
		}else{
			viewData.put("username", name);
			viewData.put("password", pwd);
			viewData.put("msg", "输入的验证码错误!");
			view.addAllObjects(viewData);
			view.setViewName("forward:/login_show"); 
			return view;
		}
		
	}
	@RequestMapping("/login/logout.action")
	public String logOut(){
		Enumeration<String> em = getSession().getAttributeNames();
		while(em.hasMoreElements()) {
			getSession().removeAttribute(em.nextElement().toString());
		}
		getSession().removeAttribute(GlobalConstants.USER_SESSION);
		getSession().invalidate();
		return "/login/login";
	}
	
	@RequestMapping("/user_info")
	@ResponseBody
	public User getUserInfo(){
		return getUser();
	}
	@RequestMapping("/login/uname_add_exist.action")
	@ResponseBody
	public Map<String,Object> unameAddExist(String uname){
		viewData.put("result", getLoginService().unameAddExist(uname));
		return viewData;
	}
	@RequestMapping("/login/register.action")
	public Map<String,Object> userRegister(String uname,String upwd,String email,
			String phone){
		getLoginService().addUser(uname, upwd, email, phone, getRequest().getRemoteAddr());
		viewData.put("result", true);
		return viewData;
	}
	
}
